#version 330 core
//uniform sampler2D qt_Texture0;
struct GEO_OUT
{
    //世界空间坐标
    vec3 vertex;
    //模型控件法线
    vec3 normal;
    //纹理坐标
    vec2 texcoord;
};
in GEO_OUT geo_out;
out vec4 FragColor;


struct Material {
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
    vec3 emission;

    float shininess;
};
struct ParallelLight {
    vec3 direction;
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};
struct SegmentLight {
    vec3 position0;
    vec3 position1;
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};

uniform vec3 viewPos;
uniform Material material;
///平行光
uniform ParallelLight parallellight;
///线段光
uniform SegmentLight segmentlight;

struct FanStruct
{
  bool show;
  float midA;
  float maxA;
  float edgA;
  vec3 Color;
};
uniform FanStruct fan;


void main(void)
{
    vec3 ambient  = parallellight.ambient  * material.ambient;

    vec3 norm = normalize(geo_out.normal);
    vec3 lightDir = normalize(parallellight.direction);

    float diff = max(dot(norm, -lightDir), 0.0);
    vec3 diffuse = parallellight.diffuse * diff*material.diffuse;


    //摄像机方向向量
    vec3 viewDir = normalize(viewPos - geo_out.vertex);
    //反射光向量
    vec3 reflectDir = reflect(lightDir, norm);
    //视角与法线夹角大于90度 或者 光线与法线夹角大于90  都不反光
    float sign1 =clamp(sign(dot(viewDir, norm)),0,1);
    float sign2 =clamp(sign(dot(-lightDir, norm)),0,1);

    float spec = pow(max(dot(viewDir, reflectDir)*sign1*sign2, 0.0), material.shininess);
    vec3 specular=parallellight.specular * spec * material.specular;

    vec3 result = ambient + diffuse + specular + material.emission;

    {
//        vec3 np0f=normalize(geo_out.vertex-segmentlight.position0);
//        vec3 np1f=normalize(geo_out.vertex-segmentlight.position1);
//        float seg=length(np0f-np1f)/2;
//        vec3 seglightDir=normalize(np0f+np1f);
//        vec3 segreflectDir = reflect(seglightDir, norm);


//        float diff = max(dot(norm, -seglightDir), 0.0);

//        diff=pow(diff, 3);
//        vec3 diffuse = segmentlight.diffuse * diff*material.specular;
//        result+=diffuse;
    }
    if(fan.show)
    {
        vec2 vtexture=normalize(vec2(geo_out.texcoord*2-1));

        vec2 vmid=vec2(sin(fan.midA),cos(fan.midA));
        vec2 vstop=vec2(sin(fan.maxA),cos(fan.maxA));

        vec2 vedg=vec2(sin(fan.maxA+fan.edgA),cos(fan.maxA+fan.edgA));

        float mindot=dot(vmid,vstop);
        float edgdot=dot(vmid,vedg);

        float signfan=smoothstep(edgdot,mindot,dot(vtexture,vmid));
        float singlen=smoothstep(1.0,0.96,length(geo_out.texcoord*2-1));

        signfan=clamp(signfan,0,1);
        singlen=clamp(singlen,0,1);
        //float signfan= clamp(sign(dot(vtexture,vmid)-mindot),0,1);

        result=signfan*singlen*fan.Color*material.specular+result;

    }

    FragColor = vec4(result,1);
}
